package mo.leetcode_top;

import mo.common.TreeNode;

import java.util.*;

public class L102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        res.add(Collections.singletonList(root.val));
        LinkedList<TreeNode> child = new LinkedList<>();
        if (root.left != null) {
            child.add(root.left);
        }
        if (root.right != null) {
            child.add(root.right);
        }
        while (!child.isEmpty()) {

            List<Integer> level = new ArrayList<>();
            int size = child.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = child.removeFirst();
                level.add(node.val);
                if (node.left != null) {
                    child.add(node.left);
                }
                if (node.right != null) {
                    child.add(node.right);
                }
            }
            res.add(level);
        }
        return res;
    }

}
